package com.tools.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        // 填充创建时间和更新时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 填充创建人（实际项目中从登录上下文获取）
//        String currentUser = UserContext.getCurrentUser(); // 自定义用户上下文工具类

        this.strictInsertFill(metaObject, "createUserId", String.class, "1");
        this.strictInsertFill(metaObject, "createUser", String.class, "admin");
        this.strictInsertFill(metaObject, "updateUserId", String.class, "1");
        this.strictInsertFill(metaObject, "updateUser", String.class, "admin");
    }

    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        // 只更新时间和操作人
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

//        String currentUser = UserContext.getCurrentUser();
        this.strictUpdateFill(metaObject, "updateUserId", String.class, "1");
        this.strictUpdateFill(metaObject, "updateUser", String.class, "admin");
    }
}
